from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import re

url="https://www.xxsy.net/chapter/25866531901067904/69470529228165448"


dirver=webdriver.Chrome()
dirver.get(url)

time.sleep(1)
try:
    # 尝试执行的代码块
    # 遍历读取章节
    dou_luo_xiao_shuo = {'name': '斗罗'}
    wen_zhang = []
    for i in range(10):
        if i>0:
            #点击下一章读取
            next_button = dirver.find_element(By.PARTIAL_LINK_TEXT, "下一章")
            next_button.click()
            close_buttons = dirver.find_elements(By.TAG_NAME, "button")
            button = driver.find_element(By.XPATH, "//button[contains(text(), '关闭')]")
            button.click()
            for close_button in close_buttons:
                if close_button.text=='关闭':
                    close_button.click()
            time.sleep(1)
        content = dirver.find_element(By.ID, "content")
        h1_list = dirver.find_elements(By.TAG_NAME, "h1")
        p_list = dirver.find_elements(By.TAG_NAME, "p")
        content_list = []
        for h1 in h1_list:
            content_list.append(h1.text)
            break;
        for p in p_list:
            content_list.append(p.text)
        wen_zhang.append('\n'.join(content_list))

    dou_luo_xiao_shuo['content'] = wen_zhang
    print('小书名称：', dou_luo_xiao_shuo.get('name'))
    for p in dou_luo_xiao_shuo.get('content'):
        print(p)

except Exception:
    # 当指定类型的异常被抛出时执行的代码块
    dirver.quit()
else:
    # 如果没有异常发生，执行的代码块
    pass
finally:
    # 无论是否发生异常，都会执行的代码块
    dirver.quit()






